#!/usr/bin/env python
#coding:utf-8
import pkg_resources
import sys
import web
import Image
from StringIO import StringIO
import calendar,time
import re

import util
import common
from feeds import pushfeed

tpls = util.tpls

web.config.debug = False

urls=(
	'/addvideo','addvideo',
	'/editvideo/(.*)','editvideo',
	'/uploadicon','icon',
	'/(.*)','user',
)

def getuid(c=None):
	if not c:
		c = common.getdb().cursor()
	uid = web.cookies().get('uid')
	md5 = web.cookies().get('md5')
	if uid and md5:
		c.execute('select md5,nickname from ac_upers where uid=%s',int(uid))
		x = c.fetchone()
		if x and x[0]==md5:
			uid = int(uid)
		else:
			uid = 0
	return uid

class editvideo:
	def GET(self,arg):
		try:
			referer = web.ctx.env.get('HTTP_REFERER')
		except:
			referer = '/'
		try:
			id = int(arg)
		except:
			return util.error_page(u'参数错误')
		uid = getuid()
		if not uid:
			return util.error_page(u'请先登录后再修改资源','/login/')
		try:
			c = common.getdb().cursor()
			c.execute('''select title,abstract,category,part,uid
				from ac_threads left join ac_videos using (id)
				where id=%s''',(id,) )
			title,abstract,category,part,thisuid = c.fetchone()
			if thisuid != uid:
				return util.error_page(u'只有UP主才能修改自己的资源',referer)
			title = title.decode('utf-8')
			abstract = abstract.decode('utf-8')
			category = category.decode('utf-8')
			parts = []
			for i in range(1,part+1):
				partid = float('%d.%03d'%(id,i))
				c.execute('select title,flashvars,vvid from ac_parts where partid=%s',(partid,))
				ttl,flashvars,vvid = c.fetchone()
				ttl = ttl.decode('utf-8')
				if 'type=' in flashvars:
					start = flashvars.find('type=')+5
					end = flashvars[start:].find('&')
					if end == -1:
						end = 65535
					type = flashvars[start:end]
				elif 'file=' in flashvars:
					type = 'file'
				else:
					type = 'sina'

				if type == 'sina':
					flvurl = 'http://you.video.sina.com.cn/b/%s-1442748650.html' % vvid
				elif type == 'youku':
					flvurl = 'http://v.youku.com/v_show/id_%s.html' % vvid
				elif type == 'file':
					start = flashvars.find('file=')+5
					end = flashvars[start:].find('&')
					if end == -1:
						end = 65535
					flvurl = flashvars[start:end]
				else:
					flvurl = ''
				parts.append( [type,flvurl,ttl] )
			# variable for user_header.html
			c.execute('''select nickname,brief 
				from ac_upers left join acu_infos using (uid)
				 where uid=%s''',(uid,))
			nickname,brief = c.fetchone()
			nickname = nickname.decode('utf-8')
			brief = brief.decode('utf-8')
			html = tpls.get_template('user_addvideo.html').render(nickname=nickname,brief=brief,uid=uid,vid=uid,title=title,abstract=abstract,category=category,parts=parts,id=id)
			return html
		except Exception as what:
			return util.error_page(u'出错了：%s'%repr(what).replace('"',"'"))
		

class addvideo:
	def GET(self):
		uid = getuid()
		if not uid:
			return util.error_page(u'请先登录后再发新资源','/login/')
		try:
			c = common.getdb().cursor()
			# variable for user_header.html
			c.execute('''select nickname,brief 
				from ac_upers left join acu_infos using (uid)
				 where uid=%s''',(uid,))
			nickname,brief = c.fetchone()
			if brief == None:
				c.execute('''insert into acu_infos (uid,sex,location,dateofbirth,interests,brief,signature)
							values (%s,'','','1900-01-01','','','')''',(uid,))
				brief = ''
			else:
				nickname = nickname.decode('utf-8')
				brief = brief.decode('utf-8')
			html = tpls.get_template('user_addvideo.html').render(nickname=nickname,brief=brief,uid=uid,vid=uid,title='',category='',abstract='',parts=[],id='')
			return html
		except Exception as what:
			return util.error_page(u'出错了：%s'%repr(what).replace('"',"'"))
	def POST(self):
		uid = getuid()
		if not uid:
			return util.error_page(u'请先登录后再发新资源','/login/')
		try:
			referer = web.ctx.env.get('HTTP_REFERER')
		except:
			referer = '/'
		c = common.getdb().cursor()
		i = web.input(litpic={})
		try:
			if not (i.title and i.description and i.cat and i.txtRow1):
				return util.error_page(u'请把信息填写完整',referer)
			title = i.title.encode('utf-8')
			now = int(calendar.timegm(time.gmtime())+3600*8)
			abstract = i.description.encode('utf-8')
			category = i.cat.encode('utf-8')
			if category == '0':
				return util.error_page(u'请选择分类',referer)
			if i.id:
				id = int(i.id)
				c.execute('''replace into ac_threads 
					(id,title,date,uid,abstract,category,url,visible,osite)
					values (%s,%s,%s,%s,%s,%s,%s,%s,%s)''',
					(id,title,now,uid,abstract,category,'',0,'avfun'))
			else:
				c.execute('''insert into ac_threads 
					(title,date,uid,abstract,category,url,visible,osite)
					values (%s,%s,%s,%s,%s,%s,%s,%s)''',
					(title,now,uid,abstract,category,'',0,'avfun'))				
				c.execute('select last_insert_id()')
				id = c.fetchone()[0]
			part = 0
			parts = ''
			for k in range(1,1000):
				try: 
					i['txtRow%d'%k]
				except:
					break
				part += 1
				if i['ttlRow%d'%k]:
					title = i['ttlRow%d'%k].encode('utf-8')
				else:
					if k==0:
						title = title
					else:
						title = 'PART %d'%k
				parts += '%d.%03d`%s`' % (id,k,title)
				type = i['selRow%d'%k]
				flvurl = i['txtRow%d'%k]
				try:
					if type == 'youku':
						flashvars = 'type=youku'
						if flvurl.startswith('http://v.youku.com'):
							vvid = re.compile('id_(.*)\.html').search(flvurl).group(1)
						elif flvurl.startswith('http://player.youku.com/'):
							vvid = flvurl.split('/')[-2]
						else:
							return util.error_page(u'YOUKU链接格式错：请参考小贴士说明填写',referer)
					elif type == 'sina':
						flashvars = ''
						vvid = flvurl.split('/')[-1].split('-')[0]
					elif type == 'file':
						flashvars = 'file=%s'%flvurl
						vvid = ''
				except Exception as what:
					return util.error_page(u'视频链接格式错：%s'%repr(what).replace('"',"'"),referer)
				partid = float('%d.%03d'%(id,k))
				c.execute('replace into ac_parts (partid,title,vxml,flashvars,vvid) values (%s,%s,%s,%s,%s)',
					(partid,title,'',flashvars,vvid) )
			content = abstract
			c.execute('replace into ac_videos (id,part,parts,content) values (%s,%s,%s,%s)',
				(id,part,parts,content) )
			if not i.id:
				c.execute('replace into ac_stats (id,clicks,comments,subs) values (%s,0,0,0)',(id,))
			try:
				if i.litpic != {}:
					sid = str(id)
					imgfile = StringIO( i['litpic'].file.read() )
					im = Image.open(imgfile)
					im = im.convert('RGB')
					im = im.resize((120,90))
					thumbfile = common.PATH + '/thumbs/%s/%s/%s.jpg' % (sid[:1],sid[1:3],sid)
					common.ensure_dir(thumbfile)
					im.save(thumbfile)
			except Exception as what:
				#	return util.error_page(u'缩略图保存错误：%s'%repr(what).replace('"',"'"),referer)
				pass
			if not i.id:
				pushfeed(uid,'发布','',c=c,id=id)
			return util.jump_page(u'发表成功','/user/%d/videos/all/1'%uid)
		except Exception as what:
			c.execute('delete from ac_threads where id=%s',(id,))
			return util.error_page(u'投递出错：%s'%repr(what).replace('"',"'"))
		

class icon:
	def GET(self):
		uid = web.cookies().get('uid')
		if not uid:
			return util.error_page(u'请先登录再上传照片……','/login/')
		try:
			referer = web.ctx.env.get('HTTP_REFERER')
		except:
			referer = '/'
		return """<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head><body>
<form method="POST" enctype="multipart/form-data" action="">
请自行裁剪为100x100大小，否则会被自动缩放为100x100<br/>
<input type="file" name="myfile" />
<input type="hidden" name="referer" value="%s" />
<input type="submit" value="上传"/>
</form>
</body></html>""" % referer
	def POST(self):
		uid = web.cookies().get('uid')
		if not uid:
			return util.error_page(u'请先登录再上传照片……','/login/')
		x = web.input(myfile={},referer='/')
		try:
			imgfile = StringIO( x['myfile'].file.read() )
			im = Image.open(imgfile)
			im = im.resize((100,100))
			filename = common.PATH + '/icon/%s/%s/%s.jpg'%(uid[:1],uid[1:3],uid)
			common.ensure_dir(filename)
			im.save(filename)
		except Exception as what:
			return util.error_page(u'出错了：%s'%what.__srt__())
		return util.jump_page(u'上传成功，返回用户主页中……','/user/%s'%str(uid))

def video(uid,arg):
	ecat,curpage = arg.split('/')[1:]
	vid = web.cookies().get('uid')
	if vid:
		vid = int(vid)
	else:
		vid = 0
	try:
		referer = web.ctx.env.get('HTTP_REFERER')
	except:
		referer = '/'
	try:
		c = common.getdb().cursor()
		# variable for user_header.html
		c.execute('''select nickname,brief 
			from ac_upers left join acu_infos using (uid)
			 where uid=%s''',(uid,))
		nickname,brief = c.fetchone()
		nickname = nickname.decode('utf-8')
		brief = brief.decode('utf-8')
		# videos
		c.execute('''select id,title,date,category,osite,
							clicks+avclicks,comments+avcomments,subs,marks
					from ac_threads left join ac_stats using(id)
					where uid=%s order by date desc''',(uid,) )
		videos = []
		count = [0,0,0,0,0,0,0,0]
		for x in c.fetchall():
			ecat2 = common.catz2e(x[3])
			if ecat == ecat2 or ecat == 'all':
				videos.append([
					x[0],x[1].decode('utf-8')[:25],
					ecat2,x[3].decode('utf-8'),
					common.int2timestr(x[2]),x[4],
					x[5],x[6],x[7],x[8]				
				])
			#count
			count[0] += 1
			if x[3] == '动画': 
				count[1]+=1
			elif x[3] == '音乐':
				count[2]+=1
			elif x[3] == '游戏':
				count[3]+=1
			elif x[3] == '娱乐':
				count[4]+=1
			elif x[3] == '番影':
				count[5]+=1
			elif x[3] == '文章':
				count[6]+=1
			else:
				count[7]+=1
		html = tpls.get_template('user_video.html').render(uid=uid,vid=vid,nickname=nickname,brief=brief,videos=videos,count=count,ecat=ecat)
		return html
	except Exception as what:
		return util.error_page(u'渲染错误：%s'%what.__str__().replace('"',"'"),referer)
	return util.error_page(u'少女傲娇中')

class user:
	def GET(self,arg):
		try:
			ip = web.ctx.environ['HTTP_X_FORWARDED_FOR']
		except:
			ip = 'unknown'
		if '/' in arg:
			uid,arg = arg.split('/',1)
		else:
			uid = arg
			arg = ''
		try:
			referer = web.ctx.env.get('HTTP_REFERER')
		except:
			referer = '/'
		if uid == '0':
			return util.error_page(u'此用户不存在',referer)
		# choose submode
		if arg.startswith('video'):
			return video(uid,arg)
		try:
			c = common.getdb().cursor()
			# recording visits
			vuid = web.cookies().get('uid')
			if vuid:
				vuid = int(vuid)
			else:
				vuid = 0
			if int(vuid) != int(uid) and int(vuid):
				if pushfeed(int(vuid),'访问','',c=c,vid=int(uid)):
					c.execute('insert into acu_visitors (uid,vid) values (%s,%s)',(int(uid),int(vuid)))
			#basic info
			uid = int(uid)
			c.execute('''select nickname,sex,location,dateofbirth,interests,brief,signature,rank
						from ac_upers right join acu_infos using (uid)
						where uid=%s''',(uid,))
			x = c.fetchone()
			if not x:
				c.execute('''insert into acu_infos (uid,sex,location,dateofbirth,interests,brief,signature)
							values (%s,'','','1900-01-01','','','')''',(uid,))
				c.execute('''select nickname,sex,location,dateofbirth,interests,brief,signature,rank
						from ac_upers right join acu_infos using (uid)
						where uid=%s''',(uid,))
				x = c.fetchone()
			nickname,sex,location,dateofbirth,interests,brief,signature,rank = (x[0].decode('utf-8'),
				x[1].decode('utf-8'),x[2].decode('utf-8'),x[3].isoformat(),x[4].decode('utf-8'),
				x[5].decode('utf-8'),x[6].decode('utf-8'),x[7] )
			#feed
			c.execute('''select type,arg,showmsg,url,urlname,date+INTERVAL 4 HOUR from acu_feeds 
							where uid=%s order by date desc limit %s''',(uid,common.USER_FEEDS))
			xd = c.fetchall()
			feeds = []
			for x in xd:
				feeds.append( [x[0].decode('utf-8'), x[1].decode('utf-8'), x[2].decode('utf-8'),
					x[3].decode('utf-8'), x[4].decode('utf-8'), x[5]] )
			#comments
			c.execute('''select vid,acu_comments.date,content,nickname from 
				acu_comments left join ac_upers on (acu_comments.vid=ac_upers.uid)
				where acu_comments.uid=%s order by acu_comments.date desc limit %s''',(uid,common.USER_COMMENTS))
			xd = c.fetchall()
			messages = []
			for x in xd:
				messages.append( [x[0],x[1],x[2].decode('utf-8'),x[3].decode('utf-8')] )
			#visitors
			c.execute('''select vid,acu_visitors.date+INTERVAL 4 HOUR,nickname from
					acu_visitors left join ac_upers on (acu_visitors.vid=ac_upers.uid)
					where acu_visitors.uid=%s order by acu_visitors.date desc limit %s''',(uid,common.USER_VISITORS))
			xd = c.fetchall()
			visitors = []
			for x in xd:
				visitors.append( [x[0],x[1],x[2].decode('utf-8')] )			
			#friends
			c.execute('''select fids from acu_friends where uid=%s''',(uid,))
			fids = c.fetchone()
			friends = []
			if fids:
				fids = [ int(x) for x in fids.split('`') ]
				wherefids = '(' + ','.join(fids) + ')'
				c.execute('''select uid,nickname from ac_upers where uid in %s''',(wherefids,))
				friends = [ [x[0],x[1].decode('utf-8')] for x in c.fetchall() ][:common.USER_FRIENDS]
			#videos
			c.execute('select count(*) from ac_threads where uid=%s',(int(uid),))
			videos = c.fetchone()
			if videos:
				videos = videos[0]
			else:
				videos = 0
			#render
			html = tpls.get_template('user_home.html').render(friends=friends,visitors=visitors,messages=messages,feeds=feeds,uid=uid,nickname=nickname,sex=sex,location=location,dateofbirth=dateofbirth,interests=interests,brief=brief,signature=signature,vid=vuid,videos=videos,rank=rank)
			return html
		except Exception as what:
			return util.error_page(u'解析出错：%s'%what.__str__().replace('"',"'"))
		return util.jump_page(u'少女傲娇中')

app_user = web.application(urls, globals())

#if __name__ == '__main__':
#	web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr)
#	app_user.run()
